10. Enable Settings Button

L6 A10 Enable Settings Button

In this step, you will add a button on the home screen that allows the user to navigate to the settings screen. The settings screen will let the user pick what kind of fun fact they want displayed on the home screen. From the settings screen, they can either choose to see facts about Android or facts about the state of California.

  1. In fragment_main.xml, add a Settings button nested in the ConstraintLayout and position it at the top right corner of the screen.

fragment_main.xml

<TextView
       android:id="@+id/settings_btn"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_margin="@dimen/text_margin"
       android:background="@color/colorAccent"
       android:padding="10dp"
       android:text="@string/settings_btn"
       android:textColor="#ffffff"
       android:textSize="20sp"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent"/>
  1. In nav_graph.xml, add an action inside mainFragment. The id of the action is action_mainFragment_to_customizeFragment and the destination is customizeFragment.

nav_graph.xml

<fragment
       android:id="@+id/mainFragment"
       android:name="com.example.android.firebaseui_login_sample.MainFragment"
       android:label="MainFragment">
   <action
           android:id="@+id/action_mainFragment_to_settingsFragment"
           app:destination="@id/settingsFragment"/>
</fragment>
  1. In MainFragment.kt’s onViewCreated(), set an onClickListener for settings_btn so that tapping the button will navigate the user to customizeFragment. Don’t worry if you see unresolved errors as you implementation action! If you see unresolved errors, you can recompile the app from the Build menu to generate and use the new navigation actions you just created in the xml.

MainFragment.kt

binding.settingsBtn.setOnClickListener {
   val action = MainFragmentDirections.actionMainFragmentToSettingsFragment()
   findNavController().navigate(action)
}
  1. Recompile and relaunch the app If everything went well, there should now be a functional Settings button on the top right corner. Clicking on the button should take you to the Settings screen, and click the back button of the Android device should bring you back to the home screen. The Settings screen only has one option to let the user choose what type of fun fact they want to see displayed on the home screen.